package org.example.controller;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import org.example.pojo.Emp;
import org.example.service.EmpService;
import org.example.util.ResultMap;
import org.jetbrains.annotations.NotNull;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.List;
import java.util.Objects;

/**
 *@ClassName: EmpController
 *@Author: CJ
 *@Date: 2021-9-2 10:51
 */
@Controller
@RequestMapping(path = "/emp")
@Api(tags = "人员管理相关接口")
public class EmpController {

    @Autowired
    private EmpService empService;

    /**
     * 主数据源test1负责写入数据
     *
     * @Author: CJ
     * @Date: 2021-9-2 21:24
     * @param emp:
     * @return: org.example.util.ResultMap
     */
    @PostMapping(path = "/addEmp")
    @ResponseBody
    @ApiOperation(value = "添加人员的接口")
    public ResultMap addEmp(@Valid Emp emp, @NotNull BindingResult bindingResult) {
        if (bindingResult.hasErrors()) {
            String defaultMessage = Objects.requireNonNull(bindingResult.getFieldError()).getDefaultMessage();
            return new ResultMap().fail().message(defaultMessage);
        }
        int i = empService.addEmp(emp);
        if (i < 0) {
            return new ResultMap().fail().message("添加失败");
        }
        return new ResultMap().success().message("添加成功");
    }

    /**
     * 从数据源test2负责读取数据
     *
     * @Author: CJ
     * @Date: 2021-9-2 21:28
     * @param id:
     * @return: org.example.util.ResultMap
     */
    @GetMapping(path = "/findEmp")
    @ResponseBody
    @ApiOperation(value = "查询特定人员的接口")
    @ApiImplicitParam(name = "id", value = "员工id", required = true)
    public ResultMap findEmp(@RequestParam(name = "id") Integer id) {
        Emp emp = empService.selectEmpById(id);
        if (StringUtils.isEmpty(emp)) {
            return new ResultMap().fail().message("查询失败");
        }
        return new ResultMap().success().data(emp).message("查询成功");
    }

    /**
     * 从数据源test2负责读取数据
     *
     * @Author: CJ
     * @Date: 2021-9-2 21:28
     * @return: org.example.util.ResultMap
     */
    @GetMapping("/selectAllEmp")
    @ResponseBody
    @ApiOperation(value = "查询所有人员的接口")
    public ResultMap selectAllEmp() {
        List<Emp> emps = empService.selectAll();
        if (CollectionUtils.isEmpty(emps)) {
            return new ResultMap().fail().message("查询失败");
        }
        return new ResultMap().success().data(emps).message("查询成功");
    }
}
